package com.asia5b.a5mall.middleware.logic.viewmodel.order

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import com.asia5b.a5bmall.resource.ResString
import com.asia5b.a5mall.middleware.R
import com.asia5b.a5mall.middleware.base.SimpleViewModel
import com.asia5b.a5mall.middleware.config.CountrysRepository
import com.asia5b.a5mall.middleware.event.CreateOrderEvent
import com.asia5b.a5mall.middleware.model.cart.CartAllModel
import com.asia5b.a5mall.middleware.model.cart.TransModel
import com.asia5b.a5mall.middleware.model.member.AddressModel
import com.asia5b.a5mall.middleware.model.member.HouseModel
import com.asia5b.a5mall.middleware.model.order.OrderCheckParamsModel
import com.asia5b.a5mall.middleware.utils.*
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers

/**
 * Created by zhangyuncai on 2020/1/6.
 */
class OrderPlaceActivityVM : SimpleViewModel() {

    //立即购买(true/商品详情购买,false/购物车购买)
    var isBuyNow = false

    var addressModelList: ArrayList<AddressModel>? = null

    fun getWay(): String {
        return (isBuyNow).judge("BUY_NOW", "CART")
    }

    /*
    https://apimall.asiajy.com/buyer/trade/create?client=WAP&house_id=11&way=BUY_NOW&goodscata_id=11
    创建订单
     */
    fun createOrder(map: MutableMap<String, Any>) {
        val goodscata_id = map["goodscata_id"] as Int
        val house_id = map["house_id"] as Int
        if (goodscata_id <= 0) {
            showMessage(ResString.get(R.string.请选择运输方式))
            return
        }
        if (house_id <= 0) {
            showMessage(ResString.get(R.string.请选择仓库))
            return
        }
        val observable = tradeApi.create(map)
                .flatMap { orderCreateResModel ->
                    getEventBus().post(CreateOrderEvent())
                    tradeApi.getTradeSerialNo(order_sn = "${orderCreateResModel.trade_sn}", trade_type = "trade")
                }
                .map { tradeSerialNoResult ->
                    tradeSerialNoResult.string()
                }

        baseSubscribe(observable, Consumer { tradeSerialNo ->
            showMessage(R.string.订单创建成功)
//            providerView().createOrderResult(tradeSerialNo)
            createOrderResultLiveData.value = tradeSerialNo
        })

        /*
        TODO http://47.88.223.5:4001/trade/orders/a5bpay/order/20200220000012
        返回一个跳转地址
        返回:http://47.74.183.145:81/payRedirect?token=eyJzaWduVGltZSI6MTU4MjE4MDQ4OSwic2lnbiI6IjAyNjk2MDk3NjUwZTY5 NGU4MWVlM2YwYTZlOWJhZjI2IiwidHJhZGVTZXJpYWxObyI6IjIwMjAwMjIw MTAwMDAxMTAyNjQ0ODIifQ==
         */
    }

    val createOrderResultLiveData = MutableLiveData<String>()
    fun setRemark(remark: String) {
        baseSubscribe(tradeApi.setRemark(remark), Consumer {
            showMessage(ResString.get(R.string.添加订单备注成功))
        })
    }


    /**
     * 设置地址
     */
    fun setAddress(map: MutableMap<String, Any>, addressModel: AddressModel) {
        dddLog("设置地址:setAddress")
        val observable = tradeApi.setAddress(addressModel.addr_id)
                .map {
                    1
                }
        getOrderDetail(map, observable)
    }

    fun getOrderDetail(map: MutableMap<String, Any>) {
        getOrderDetail(map, Observable.just(1))
    }

    /**
     * //todo 获取商品列表->获取地址列表->获取仓库列表->获取国际运输方式->获取价格详细
     */
    private fun getOrderDetail(map: MutableMap<String, Any>, observableStart: Observable<Int>) {
        dddLog("一切以获取商品列表开始:getOrderDetail")
        //一切以获取商品列表开始
        var observable = observableStart
                //获取商品列表
                .flatMap {
                    return@flatMap getGoods(map)
                }
                //获取地址列表
                .flatMap {
                    val address_id = map["address_id"]!! as Int
                    if (address_id <= 0) {
                        return@flatMap getAddress(map)
                    }
                    return@flatMap Observable.just(1)
                }
                //获取仓库列表
                .flatMap {
                    val house_id = map["house_id"]!! as Int
                    if (house_id <= 0) {
                        return@flatMap getHouse(map)
                    }
                    return@flatMap Observable.just(1)
                }
                //获取国际运输方式
                .flatMap {
                    val goodscata_id = map["goodscata_id"]!! as Int
                    if (goodscata_id <= 0) {
                        return@flatMap getTrans(map)
                    }
                    return@flatMap Observable.just(1)
                }
                //获取价格详细
                .flatMap {
                    return@flatMap cartApi.getPrice(map)
                }
        baseSubscribe(observable, Consumer { cartAllModel ->
//            providerView().setPriceView(cartAllModel)
            setPriceViewLiveData.value = cartAllModel
        })
    }

    val setPriceViewLiveData = MutableLiveData<CartAllModel>()

    /**
     * https://apimall.asiajy.com/buyer/trade/carts/checked?way=BUY_NOW
     * 获取商品列表
     */
    fun getGoods(map: MutableMap<String, Any>): Observable<Int> {
        dddLog("获取商品列表:getGoods")
        return cartApi.getCartData("checked", getWay())
                .map { cartAllModel ->
                    Observable.just(cartAllModel)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(Consumer {
//                                providerView().setGoodsView(it)
                            }, Consumer { })
                    return@map 1
                }
    }

    var orderCheckParamsModel: OrderCheckParamsModel? = null

    /**
     * 获取地址
     */
    fun getAddress(map: MutableMap<String, Any>): Observable<Int> {
        dddLog("获取地址:getAddress")
        //todo 获取上次购买的一些记录,譬如上次购买时用的地址,用的仓库
        var observable: Observable<ArrayList<AddressModel>>
        if (addressModelList != null) {
            observable = Observable.just(addressModelList!!)
        } else {
            observable = memberApi.getAddressList()
        }
        return observable
                .flatMap {
                    addressModelList = it
                    tradeApi.getParam()
                }
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterNext {
                    map["address_id"] = it.addressId
                    if (it.addressId > 0 && addressModelList != null && addressModelList!!.size > 0) {
                        for (addressModel in addressModelList!!) {
                            if (addressModel.addr_id == it.addressId) {
                                map["region_id"] = addressModel.region_id
                                map["city_id"] = addressModel.cityId
//                                providerView().setAddressView(addressModel)
                                setAddressViewLiveData.value = addressModel
                                break
                            }
                        }
                    }
                    orderCheckParamsModel = it
//                    providerView().setParamsView(it)
                    setParamsViewLiveData.value = it
                }
                .observeOn(Schedulers.io())
                .flatMap {
                    Observable.just(1)
                }

    }

    val setAddressViewLiveData = MutableLiveData<AddressModel>()
    val setParamsViewLiveData = MutableLiveData<OrderCheckParamsModel>()

    /**
     * 获取仓库
     */
    fun getHouse(map: MutableMap<String, Any>): Observable<Int> {
        dddLog("获取仓库:getHouse")
        return CountrysRepository.anyOb<ArrayList<HouseModel>>(CountrysRepository.house)
                .map { houseModelList ->
                    if (orderCheckParamsModel != null && !TextUtils.isEmpty(orderCheckParamsModel!!.goodscata_id)) {
                        for (houseModel in houseModelList) {
                            if (TextUtils.equals("${houseModel.id}", orderCheckParamsModel!!.goodscata_id)) {
                                //默认上一次购买的仓库
                                map["house_id"] = houseModel.id
                                Observable.just(houseModel)
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(Consumer {
//                                            providerView().setHouseList(houseModelList)
                                            setHouseListLiveData.value = houseModelList
                                        }, Consumer { })
                                return@map 1
                            }
                        }
                    }
                    if (!houseModelList.isNullOrEmpty()) {
                        val houseModel = houseModelList!![0]
                        //默认第一个仓库
                        map["house_id"] = houseModel.id
                        Observable.just(houseModel)
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(Consumer {
//                                    providerView().setHouseList(houseModelList)
                                    setHouseListLiveData.value = houseModelList
                                }, Consumer { })
                    }
                    return@map 1
                }
    }

    val setHouseListLiveData = MutableLiveData<ArrayList<HouseModel>>()

    /**
     * 获取运输方式
     */
    fun getTrans(map: MutableMap<String, Any>): Observable<Int> {
        dddLog("获取运输方式:getTrans")
        return cartApi.getTrans(map)
                .map { cartAllModel ->
                    val transportations = cartAllModel.transportations
                    //默认第一个运输方式
                    Observable.just(transportations)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(Consumer {
                                if (!transportations.isNullOrEmpty()) {
                                    map["goodscata_id"] = transportations!![0].id
                                    setTransferListLiveData.value = transportations
                                } else {
                                    setTransferListLiveData.value = null
                                }
                            }, Consumer { })

                    return@map 1
                }
    }

    val setTransferListLiveData = MutableLiveData<ArrayList<TransModel>>()
    val userCouponResultLiveData = MutableLiveData<Boolean>()

    /*
    https://apimall.asiajy.com/buyer/trade/promotion/83/seller/263/coupon?way=BUY_NOW
     */
    fun userCoupon(seller_id: Int, memberCouponId: Int, isBuyNow: Boolean) {
        baseSubscribe(tradeApi.useCoupon(seller_id, memberCouponId, getWay()), Consumer {
//            providerView().userCouponResult()
            userCouponResultLiveData.value = true
        })
    }
}